package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type CourseListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCourseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CourseListLogic {
	return &CourseListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CourseListLogic) CourseList(req *types.CourseListReq) (resp *types.CourseListResp, err error) {
	// todo: add your logic here and delete this line
	url := "https://harmonyosdev.csdn.net/v1/course/homeCourseList"

	res, err := httpc.Do(l.ctx, http.MethodPost, url, req)
	if err != nil {
		l.Errorf("Failed to make HTTP request: %v", err)
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body: %v", err)
		return nil, err
	}

	// 检查HTTP状态码
	if res.StatusCode != http.StatusOK {
		l.Errorf("Unexpected status code: %d", res.StatusCode)
		return nil, fmt.Errorf("unexpected status code: %d", res.StatusCode)
	}

	var str bytes.Buffer
	_ = json.Indent(&str, []byte(body), "", "    ")
	l.Debugf("formated: ", str.String())

	// 解析JSON数据
	jsonResult := gjson.ParseBytes(body)
	// 检查响应状态码
	code := jsonResult.Get("code").Int()
	if code != 200 {
		return nil, fmt.Errorf("请求失败, code: %d, msg: %s", code, jsonResult.Get("msg").String())
	}

	// 解析数据部分
	data := jsonResult.Get("data")
	total := data.Get("total").Int()
	contentList := data.Get("contentList").Array()

	// 创建 CourseListResp 结构体
	resp = &types.CourseListResp{
		Code: 0,
		Msg:  jsonResult.Get("msg").String(),
		Data: types.CourseList{
			Total: int(total),
		},
	}

	// 解析课程列表
	for _, item := range contentList {
		course := types.Course{
			CourseId:     item.Get("courseId").String(),
			LecturerId:   int(item.Get("lecturerId").Int()),
			Title:        item.Get("title").String(),
			Type:         int(item.Get("type").Int()),
			ResourceType: int(item.Get("resourceType").Int()),
			Views:        int(item.Get("views").Int()),
			Duration:     int(item.Get("duration").Int()),
			LessonCount:  int(item.Get("lessonCount").Int()),
			Description:  item.Get("description").String(),
			CreatedAt:    item.Get("createdAt").String(),
			Ext: types.Ext{
				Cover:     item.Get("ext.cover").String(),
				TargetUrl: item.Get("ext.targetUrl").String(),
			},
		}
		resp.Data.ContentList = append(resp.Data.ContentList, course)
	}

	return resp, nil
}
